﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using LimitOrderBookSim.Assets;
using LimitOrderBookSim.Commons;
using LimitOrderBookSim.Model.Markets;

namespace LimitOrderBookSim.Model.Mock
{
   public class Player
    {
       Random random;
       List<Market> _markets;
       List<String> _events;
       public bool IsPlaying { get; set; }

       public Player(List<Market> markets)
       {
           _markets = markets;
           _events = new List<string>();

           foreach (Market m in _markets)
           {
               foreach (Event e in m.Events)
               {
                   foreach (Contract c in e.Contract)
                   {
                       _events.Add(c.Name);
                   }
               }
           }
           
           IsPlaying = false;
           random = new Random((int)DateTime.Now.TimeOfDay.TotalMilliseconds);
       }


       public void ExecuteSim(Object obj)
       {
           IsPlaying = true;

           while (IsPlaying)
           {
               String contract = RandomContract();

               foreach (Market m in _markets)
               {
                   foreach (Event e in m.Events)
                   {
                       foreach (Contract c in e.Contract)
                       {
                           if (c.Name == contract)
                           {
                               c.Pool.Add(RandomOrder());
                           }
                       }
                   }
               }
           }
       }

       public void Play()
       {
          // ExecuteSim(null);

           Thread t = new Thread(ExecuteSim);
           t.Start();

           //ThreadPool.QueueUserWorkItem(
           // delegate
           //     {
           //       ExecuteSim(null);
           //     }
           //);

           //ThreadPool.QueueUserWorkItem(
           //    ExecuteSim, null);
       }

       private String RandomContract()
       {
           return
               _events[random.Next(0, _events.Count)];
       }

       public Message RandomOrder()
       {
           Message msg = new Message()
           {
               Event = EVENT.SUBMISSION,
               Timestamp = DateTime.Now.Ticks,
               Order = new Order()
               {
                   ID = -1,
                   Price = Math.Round((random.NextDouble() + 0.1) * 10, 2),
                   Size = random.Next(1, 15),
                   Type = (random.Next(0, 2) == 1) ? TYPE.ASK : TYPE.BID
               }
           };

           return msg;
       }

    }
}
